
package com.example.activititest.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * ActivitiServiceController 流程建模编辑器控制类 @RequestMapping("/visual") 对应
 * src\main\resources\static\editor-app\app-cfg.js 24行
 */
@RestController
@RequestMapping("/visual")
public class ActivitiVisualController {

	private static final Logger logger = LoggerFactory.getLogger(ActivitiVisualController.class);

	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	private RepositoryService repositoryService;

	/**
	 * stencilset
	 * 对应src\\main\\resources\\static\\editor-app\\configuration\\url-config.js 24行
	 * 找出定义的模具集合
	 * 
	 * @return stencilset.json
	 */
	@RequestMapping("/editor/stencilset")
	public String getStencilset() {
		InputStream stencilsetStream = this.getClass().getResourceAsStream("/static/stencilset.json");
		try {
			return IOUtils.toString(stencilsetStream, "utf-8");
		} catch (Exception e) {
			throw new ActivitiException("Error while loading stencil set", e);
		}
	}

	/**
	 * 模型详情 对应src\\main\\resources\\static\\editor-app\\configuration\\url-config.js
	 * 28行
	 *
	 * @param modelId
	 * @return
	 */
	@RequestMapping("/model/{modelId}/json")
	public ObjectNode getEditorJson(@PathVariable String modelId) {
		ObjectNode modelNode = null;

		Model model = repositoryService.getModel(modelId);

		if (model != null) {
			try {
				if (StringUtils.isNotEmpty(model.getMetaInfo())) {
					modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
				} else {
					modelNode = objectMapper.createObjectNode();
					modelNode.put("name", model.getName());
				}
				modelNode.put("modelId", model.getId());
				ObjectNode editorJsonNode = (ObjectNode) objectMapper
						.readTree(new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
//				JsonNode jsonNode=editorJsonNode.get("properties");
//				if("process".equals(jsonNode.get("process_id").toString())) {
//					jsonNode.
//				}
//				

				modelNode.set("model", editorJsonNode);

			} catch (Exception e) {
				throw new ActivitiException("Error creating model JSON", e);
			}
		}
		return modelNode;
	}

	@RequestMapping(value = "/model/{modelId}/save")
	@ResponseStatus(value = HttpStatus.OK)
	public void saveModel(@PathVariable String modelId, @RequestParam("name") String name,
			@RequestParam("json_xml") String jsonXml, @RequestParam("svg_xml") String svgXml,
			@RequestParam("description") String description) {
		try {

			Model model = repositoryService.getModel(modelId);

			ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

			modelJson.put("name", name);
			modelJson.put("description", description);
			model.setMetaInfo(modelJson.toString());
			model.setName(name);

			repositoryService.saveModel(model);

			repositoryService.addModelEditorSource(model.getId(), jsonXml.getBytes(StandardCharsets.UTF_8));

			InputStream svgStream = new ByteArrayInputStream(svgXml.getBytes(StandardCharsets.UTF_8));
			TranscoderInput input = new TranscoderInput(svgStream);

			PNGTranscoder transcoder = new PNGTranscoder();
			// Setup output
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			TranscoderOutput output = new TranscoderOutput(outStream);
			transcoder.transcode(input, output);
			final byte[] result = outStream.toByteArray();
			repositoryService.addModelEditorSourceExtra(model.getId(), result);
			outStream.close();

		} catch (Exception e) {
			logger.error("Error saving model", e);
			throw new ActivitiException("Error saving model", e);
		}
	}

	/**
	 * 创建模型
	 * 
	 * @param response
	 * @param name     模型名称
	 * @param key      模型key
	 * @param category 类型，用户自己对流程模型的分类。
	 * @throws IOException
	 */
	@RequestMapping("/create")
	public void create(HttpServletResponse response, String name, String key, String category) throws IOException {
		if (StringUtils.isBlank(key)) {
			key = "public";
		}
		if (StringUtils.isBlank(category)) {
			category = "public";
		}
		logger.info("创建模型入参name：{},key:{}", name, key);
		Model model = repositoryService.newModel();
		ObjectNode modelNode = objectMapper.createObjectNode();
		modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
		modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, "");
		modelNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
		model.setName(name);
		model.setKey(key);
		model.setCategory(category);
		model.setMetaInfo(modelNode.toString());
		repositoryService.saveModel(model);
		createObjectNode(model);
		response.sendRedirect("/modeler.html?modelId=" + model.getId());
		logger.info("创建模型结束，返回模型ID：{}", model.getId());
	}

	/**
	 * 创建模型时完善ModelEditorSource
	 * 
	 * @param modelId
	 */
	@SuppressWarnings("deprecation")
	private void createObjectNode(Model model) {
		logger.info("创建模型完善ModelEditorSource入参模型ID：{}", model.getId());
		ObjectNode editorNode = objectMapper.createObjectNode();
		editorNode.put("id", "canvas");
		editorNode.put("resourceId", "canvas");
		ObjectNode stencilSetNode = objectMapper.createObjectNode();
		stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
		editorNode.put("stencilset", stencilSetNode);
		try {
			Map<String, String> propertiesMap = new HashMap<String, String>();
			propertiesMap.put("process_id", model.getKey());
			JsonNode propertieJsonNode = objectMapper.readValue(JSONObject.toJSONString(propertiesMap), JsonNode.class);
			editorNode.put("properties", propertieJsonNode);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			repositoryService.addModelEditorSource(model.getId(), editorNode.toString().getBytes("utf-8"));
		} catch (Exception e) {
			logger.info("创建模型时完善ModelEditorSource服务异常：{}", e);
		}
		logger.info("创建模型完善ModelEditorSource结束");
	}

	/**
	 * 跳转编辑器页面
	 * 
	 * @return
	 */
	@GetMapping("editor")
	public String editor() {
		return "modeler";
	}

}
